package com.cxh.rmsq.ui.activity.self

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.cxh.rmsq.R
import com.cxh.rmsq.common.Constant
import com.cxh.rmsq.databinding.ActivityClueListBinding
import com.cxh.rmsq.db.model.ClueBean
import com.cxh.rmsq.db.model.ClueItemBean
import com.cxh.rmsq.event.LiveEventBusCode
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.ui.BaseActivity
import com.cxh.rmsq.ui.adapter.self.ClueListAdapter
import com.cxh.rmsq.ui.adapter.self.ClueSmallListAdapter
import com.cxh.rmsq.utils.dialog.CluePopup
import com.cxh.rmsq.utils.dialog.PayPopup
import com.cxh.rmsq.utils.wechatPay
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.lang.Math.asin
import java.lang.Math.atan2
import java.lang.Math.cos
import java.lang.Math.sin

/**
 * 寻宝藏
 */
class ClueListActivity : BaseActivity(), View.OnClickListener {
    private lateinit var binding: ActivityClueListBinding

    private var locationId = ""
    private var name = ""
    private var activityName = ""
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }
    private var smallAdapter: ClueSmallListAdapter? = null
    private var midAdapter: ClueSmallListAdapter? = null
    private var highAdapter: ClueSmallListAdapter? = null
    private var listAdapter: ClueListAdapter? = null
    private var isPopup = true
    private var distance = 0
    var longitude = 0.0
    var latitude = 0.0

    private var aMap: AMap? = null
    private var markers = mutableListOf<Marker>()
    var isSigned = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityClueListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.clToolbar.setPadding(0, 0, 0, 0)
//        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        binding.mapview.onCreate(savedInstanceState)
        aMap = binding.mapview.getMap()

        // 移除缩放控件
        aMap!!.uiSettings.isZoomControlsEnabled = false
        // 禁止手势缩放
        aMap!!.uiSettings.isZoomGesturesEnabled = false

        binding.ivBack.setOnClickListener(this)
        binding.llDaka.setOnClickListener(this)
        binding.tvSign.setOnClickListener(this)
        binding.tvInvite.setOnClickListener(this)
        binding.tvExchange.setOnClickListener(this)
//        binding.tvSigned.setGradientColors(
//            Color.parseColor("#ffffff"), Color.parseColor("#666666")
//        )
        binding.tvSign.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
        binding.tvSigned.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
        binding.tvInvited.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
        binding.tvExchanged.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
        binding.tvInvite.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
        binding.tvExchange.setShadowLayer(4F, 2F, 2F, Color.parseColor("#C61A02"))
//        binding.tvInvite.setGradientColors(
//            Color.parseColor("#ffffff"), Color.parseColor("#FFE492")
//        )
//        binding.tvExchange.setGradientColors(
//            Color.parseColor("#ffffff"), Color.parseColor("#FFE492")
//        )

        activityName = intent.getStringExtra("activityName").toString()
        locationId = intent.getStringExtra("locationId").toString()
        name = intent.getStringExtra("name").toString()
        distance = intent.getIntExtra("distance", 0)//可打卡范围
        latitude = intent.getDoubleExtra("latitude", 0.0)
        longitude = intent.getDoubleExtra("longitude", 0.0)
        Log.e("locationId", locationId)

        binding.mapContainer.setScrollView(binding.nestedScrollView)

        binding.rvSmall.setLayoutManager(LinearLayoutManager(this))
        smallAdapter = ClueSmallListAdapter(1)
        binding.rvSmall.setAdapter(smallAdapter)
        smallAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (smallAdapter!!.data[position].clueType == 2) {//公里数
                val radius = smallAdapter!!.data[position].clueContent!!.toDouble() * 1000
                binding.rlTitle.isVisible = true
                binding.srlMap.isVisible = true
                binding.tvName.text = activityName

                mapMarker(radius)
                Handler().postDelayed(Runnable {
                    binding.nestedScrollView.smoothScrollTo(0, binding.nestedScrollView.height)
                },500)
            } else {
                binding.rlTitle.isVisible = false
                binding.srlMap.isVisible = false
            }
        }
        smallAdapter!!.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.tv_get -> {
                    binding.nestedScrollView.smoothScrollTo(0, binding.nestedScrollView.height)
                }
            }
        })
        binding.rvProduct.setLayoutManager(LinearLayoutManager(this))
        listAdapter = ClueListAdapter(1)
        binding.rvProduct.setAdapter(listAdapter)
        listAdapter!!.setOnItemClickListener { adapter, view, position ->
            popPay(listAdapter!!.data[position].id!!, listAdapter!!.data[position].productPrice!!)
        }

        initData()
        LiveEventBus.get(LiveEventBusCode.RECHARGE_SUCCESS_MESSAGE, String::class.java).observe(
            this
        ) {
            //支付成功请求一下账户信息
            initData()
        }
    }

    private fun mapMarker(radius: Double) {
        val marker = aMap!!.addMarker(
            MarkerOptions()
                .position(LatLng(latitude, longitude))
                //                        .title(it.data[pos].locationCode)
                //                        .snippet(it.data[pos].id.toString())
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_custom_marker_none))
        )
        markers.add(marker)

        // 添加圆形覆盖物（5公里范围）
        val circle = aMap!!.addCircle(
            CircleOptions()
                .center(marker.position)
                .radius(radius)
                .strokeColor(resources.getColor(R.color.transparent))
            /*.fillColor(Color.parseColor("#500084d3")*/)

        val points = mutableListOf<LatLng>()
        points.add(calculatePoint(marker.position, radius, 45.0)) // NE
        points.add(calculatePoint(marker.position, radius, 225.0)) // SW

        val builder = LatLngBounds.builder()
        points.forEach { builder.include(it) }
        val bounds = builder.build()

        val cameraUpdate = CameraUpdateFactory.newLatLngBoundsRect(bounds, 100, 100, 100, 100)
        aMap!!.animateCamera(cameraUpdate)

    }

    private fun initData() {
        viewModel.getUserCheckIn(locationId) {
            if (it.code == 200) {
                isSigned = it.data
            } else {
                com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
            }
        }

        viewModel.getClueList(locationId) {
            if (it.code == 200) {
                if (it.data.beginnerList!!.size > 0) {
                    smallAdapter!!.setNewInstance(it.data.beginnerList)
                    binding.tvSmall.isVisible = false
                } else {
                    binding.tvSmall.isVisible = true
                }
                if (it.data.intermediateList!!.size > 0) {//已经购买过中级线索
                    binding.midClue.isVisible = true
                    binding.rvMid.setLayoutManager(LinearLayoutManager(this))
                    midAdapter = ClueSmallListAdapter(2)
                    binding.rvMid.setAdapter(midAdapter)
                    midAdapter!!.setNewInstance(it.data.intermediateList)
                    midAdapter!!.setOnItemClickListener { adapter, view, position ->
                        if (midAdapter!!.data[position].clueType == 2) {//公里数
                            val radius = midAdapter!!.data[position].clueContent!!.toDouble() * 1000
                            binding.rlTitle.isVisible = true
                            binding.srlMap.isVisible = true
                            binding.tvName.text = activityName

                            mapMarker(radius)
                            Handler().postDelayed(Runnable {
                                binding.nestedScrollView.smoothScrollTo(0, binding.nestedScrollView.height)
                            },500)
                        } else {
                            binding.rlTitle.isVisible = false
                            binding.srlMap.isVisible = false
                        }
                    }
                } else {
                    binding.midClue.isVisible = false
                }
                if (it.data.advancedList!!.size > 0) {//已经购买过高级线索
                    binding.highClue.isVisible = true
                    binding.rvHigh.setLayoutManager(LinearLayoutManager(this))
                    highAdapter = ClueSmallListAdapter(3)
                    binding.rvHigh.setAdapter(highAdapter)
                    highAdapter!!.setNewInstance(it.data.advancedList)
                    highAdapter!!.setOnItemClickListener { adapter, view, position ->
                        if (highAdapter!!.data[position].clueType == 2) {//公里数
                            val radius =
                                highAdapter!!.data[position].clueContent!!.toDouble() * 1000
                            binding.rlTitle.isVisible = true
                            binding.srlMap.isVisible = true
                            binding.tvName.text = activityName

                            mapMarker(radius)
                            Handler().postDelayed(Runnable {
                                binding.nestedScrollView.smoothScrollTo(0, binding.nestedScrollView.height)
                            },500)
                        } else {
                            binding.rlTitle.isVisible = false
                            binding.srlMap.isVisible = false
                        }
                    }
                } else {
                    binding.highClue.isVisible = false
                }
                if (it.data.productInfoList!!.size > 0) {
                    binding.rvProduct.isVisible = true
                    val productList = mutableListOf<ClueItemBean>()
                    productList.addAll(it.data.productInfoList!!)
                    if (it.data.intermediateList!!.size == 0 && it.data.advancedList!!.size == 0) {
                        listAdapter!!.setNewInstance(productList)
                    } else {
                        if (it.data.intermediateList!!.size > 0) {//有中级
                            for (j in 0 until productList.size) {
                                if (productList[j].level == 2) {
                                    productList.remove(productList[j])
                                    break
                                }
                            }
                        }
                        if (it.data.advancedList!!.size > 0) {//有高级
                            for (j in 0 until productList.size) {
                                if (productList[j].level == 3) {
                                    productList.remove(productList[j])
                                    break
                                }
                            }
                        }

                        listAdapter!!.setNewInstance(productList)
                    }
                } else {
                    binding.rvProduct.isVisible = false
                    listAdapter!!.setNewInstance(null)
                }
            } else {
                com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
                finish()
            }
        }

        viewModel.getClueUserCount(locationId) {
            if (it.code == 200) {
                if (it.data.isZh) {//置灰
                    binding.tvSign.isVisible = false
                    binding.tvInvite.isVisible = false
                    binding.tvExchange.isVisible = false
                    binding.tvSigned.isVisible = true
                    binding.tvInvited.isVisible = true
                    binding.tvExchanged.isVisible = true
                } else {
                    if (isSigned == 0) {//未签到
                        binding.tvSign.isVisible = true
                        binding.tvSigned.isVisible = false
                    } else {
                        binding.tvSign.isVisible = false
                        binding.tvSigned.isVisible = true
                    }
                    binding.tvInvite.isVisible = true
                    binding.tvExchange.isVisible = true
                    binding.tvInvited.isVisible = false
                    binding.tvExchanged.isVisible = false
                }
//                it.data.yqCount =2
//                it.data.fxCount =2
                if (isPopup) {
                    isPopup = false
                    if (it.data.yqCount > 0) {//邀请
                        XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(
                                CluePopup(this,
                                    3,
                                    name,
                                    object : CluePopup.onClick {
                                        override fun click(s: String, s1: String) {

                                        }
                                    })
                            )
                            .show()
                    } else if (it.data.fxCount > 0) {//分享
                        XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(
                                CluePopup(this,
                                    4,
                                    name,
                                    object : CluePopup.onClick {
                                        override fun click(s: String, s1: String) {

                                        }
                                    })
                            )
                            .show()
                    }
                }
            } else {
                com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
            }
        }
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.iv_back -> {
                finish()
            }

            R.id.tv_sign -> {
                val paramsMap = HashMap<String, Any>()
                paramsMap["locationId"] = locationId
                viewModel.createSign(paramsMap) {
                    if (it.code == 200) {
                        XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(
                                CluePopup(this,
                                    1,
                                    name,
                                    object : CluePopup.onClick {
                                        override fun click(s: String, s1: String) {
                                            initData()
                                        }
                                    })
                            )
                            .show()
                    } else {
                        com.cxh.rmsq.utils.ToastUtils.showToast(it.msg.toString())
                    }
                }
            }

            R.id.tv_invite -> {
                startActivity(
                    Intent(this, InviteActivity::class.java)
                        .putExtra("locationId", locationId)
                )
            }

            R.id.tv_exchange -> {
                startActivity(
                    Intent(this, PubExchangeActivity::class.java)
                        .putExtra("locationId", locationId)
                        .putExtra("name", name)
                        .putExtra("progressId", intent.getStringExtra("progressId"))
                )
            }

            R.id.ll_daka -> {
                startActivity(
                    Intent(this, DakaLocationActivity::class.java)
                        .putExtra("activityName", activityName)
                        .putExtra("locationId", locationId)
                        .putExtra("distance", distance)
                        .putExtra("latitude", latitude)
                        .putExtra("longitude", longitude)
                        .putExtra("name", name)//碎片名称
                        .putExtra("progressId", intent.getStringExtra("progressId").toString())
                        .putExtra("activityId", intent.getStringExtra("activityId").toString())
                )
            }
        }
    }

    private fun popPay(id: Int, money: String) {
        XPopup.Builder(this@ClueListActivity)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(PayPopup(this@ClueListActivity, money,"", object : PayPopup.onClick {
                override fun click(content: String, s1: Int) {
                    val paramsMap = HashMap<String, Any>()
                    paramsMap["productId"] = id
                    paramsMap["busId"] = locationId
                    paramsMap["payWay"] = 1 //1：微信支付 2：支付宝 3：apple支付
                    paramsMap["type"] = 1 //1 藏宝 2 会员
                    viewModel.createOrder(paramsMap) {
                        if (it.code == 200) {
                            val wxapi = WXAPIFactory.createWXAPI(
                                this@ClueListActivity,
                                Constant.WECHAT_APP_ID,
                                true
                            )
                            // 将该app注册到微信
                            wxapi.registerApp(Constant.WECHAT_APP_ID)
                            if (!wxapi.isWXAppInstalled) {
                                Log.e("===", "你没有安装微信")
                                com.cxh.rmsq.utils.ToastUtils.showToast("你没有安装微信")
                                return@createOrder
                            }
                            SPUtils.getInstance().put("orderId", it.data.id.toString())
                            wechatPay(wxapi, it.data.wxPayOrderResult!!)
                        } else {
                            com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
                        }
                    }
                }
            })).show()
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }

    override fun onResume() {
        super.onResume()
        binding.mapview.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.mapview.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.mapview.onDestroy();
        markers.clear();
    }

    /**​
    * 根据中心点、距离和方位角计算目标点坐标
    * @param center 中心点经纬度
    * @param distance 距离（米）
    * @param bearing 方位角（0=正北，90=东，180=南，270=西）
    * @return 目标点经纬度
    */
    fun calculatePoint(center: LatLng, distance: Double, bearing: Double): LatLng {
        val earthRadius = 6378137.0 // 地球赤道半径（单位：米，WGS84 标准）
        val latRad = Math.toRadians(center.latitude)
        val lngRad = Math.toRadians(center.longitude)
        val angularDistance = distance / earthRadius
        val bearingRad = Math.toRadians(bearing)

        val newLatRad = asin(
            sin(latRad) * cos(angularDistance) +
                    cos(latRad) * sin(angularDistance) * cos(bearingRad)
        )

        val newLngRad = lngRad + atan2(
            sin(bearingRad) * sin(angularDistance) * cos(latRad),
            cos(angularDistance) - sin(latRad) * sin(newLatRad)
        )

        return LatLng(
            Math.toDegrees(newLatRad),
            Math.toDegrees(newLngRad)
        )
    }
}